// js/dashboard.js

let currentUser = null;
let currentActiveView = '';

// DOM Elements
const loggedInUsernameSpan = document.getElementById('loggedInUsername');
const logoutBtn = document.getElementById('logoutBtn');
const notificationArea = document.getElementById('notificationArea');
const sidebarNavLinks = document.querySelectorAll('.dashboard-sidebar nav ul li a');
const contentSections = document.querySelectorAll('.content-section');

// Views
const myOutcomesView = document.getElementById('myOutcomesView');
const createOutcomeView = document.getElementById('createOutcomeView');
const outcomeReviewView = document.getElementById('outcomeReviewView');
const userManagementView = document.getElementById('userManagementView');
const outcomeTypeManagementView = document.getElementById('outcomeTypeManagementView');

// My Outcomes Elements
const myOutcomesFilterType = document.getElementById('myOutcomesFilterType');
const myOutcomesFilterKeywords = document.getElementById('myOutcomesFilterKeywords');
const searchMyOutcomesBtn = document.getElementById('searchMyOutcomesBtn');
const exportMyOutcomesBtn = document.getElementById('exportMyOutcomesBtn');
const myOutcomesListDiv = document.getElementById('myOutcomesList');

// Create Outcome Elements
const selectOutcomeType = document.getElementById('selectOutcomeType');
const outcomeForm = document.getElementById('outcomeForm');
const currentOutcomeTypeTitle = document.getElementById('currentOutcomeTypeTitle');
const commonOutcomeFieldsDiv = document.getElementById('commonOutcomeFields'); // <-- 将用于通用字段
const specificOutcomeFieldsDiv = document.getElementById('specificOutcomeFields'); // <-- 将用于特定字段和列表
const outcomeAttachmentInput = document.getElementById('outcomeAttachment');
const importBtn = document.getElementById('importBtn');
const downloadTemplateBtn = document.getElementById('downloadTemplateBtn');

// Outcome Review Elements
const pendingOutcomesListDiv = document.getElementById('pendingOutcomesList');

// User Management Elements
const addUserBtn = document.getElementById('addUserBtn');
const userFormContainer = document.getElementById('userFormContainer');
const userForm = document.getElementById('userForm');
const userIdInput = document.getElementById('userId');
const userUsernameInput = document.getElementById('userUsername');
const userPasswordInput = document.getElementById('userPassword');
const userRoleSelect = document.getElementById('userRole');
const cancelUserEditBtn = document.getElementById('cancelUserEditBtn');
const userListDiv = document.getElementById('userList');

// Outcome Type Management Elements
const newOutcomeTypeForm = document.getElementById('newOutcomeTypeForm');
const newTypeNameInput = document.getElementById('newTypeName');
const outcomeTypesListUl = document.getElementById('outcomeTypesList');


document.addEventListener('DOMContentLoaded', () => {
    initDashboard();
});

function initDashboard() {
    currentUser = data.getCurrentUser();
    if (!currentUser) {
        window.location.href = 'index.html'; // No user logged in, redirect to login
        return;
    }

    loggedInUsernameSpan.textContent = currentUser.username;
    setupNavigation();
    setupEventListeners();
    populateOutcomeTypeSelectors();

    // Default view based on role
    if (currentUser.role === 'admin') {
        showView('outcomeReview'); // Admins usually go to review first
    } else {
        showView('myOutcomes');
    }
}

function showNotification(message, type = 'info', duration = 3000) {
    notificationArea.textContent = message;
    notificationArea.className = `notification-area ${type === 'error' ? 'error-message' : (type === 'success' ? 'success-message' : '')}`;
    notificationArea.style.display = 'block';
    setTimeout(() => {
        notificationArea.style.display = 'none';
        notificationArea.textContent = '';
    }, duration);
}

function hideAllViews() {
    contentSections.forEach(section => section.classList.add('hidden'));
    sidebarNavLinks.forEach(link => link.classList.remove('active'));
}

function showView(viewId) {
    hideAllViews();
    const targetView = document.getElementById(`${viewId}View`);
    if (targetView) {
        targetView.classList.remove('hidden');
        currentActiveView = viewId;

        // Highlight active nav link
        sidebarNavLinks.forEach(link => {
            if (link.dataset.view === viewId) {
                link.classList.add('active');
            }
        });

        // Load content for the active view
        switch (viewId) {
            case 'myOutcomes':
                renderMyOutcomes();
                break;
            case 'createOutcome':
                resetOutcomeForm();
                break;
            case 'outcomeReview':
                renderPendingOutcomes();
                break;
            case 'userManagement':
                renderUserManagement();
                resetUserForm(); // Clear user form when viewing list
                break;
            case 'outcomeTypeManagement':
                renderOutcomeTypesManagement();
                break;
            // case 'systemSettings': // Placeholder
            //     break;
        }
    }
}

function setupNavigation() {
    // Show/hide admin-only links
    const adminOnlyElements = document.querySelectorAll('.admin-only');
    adminOnlyElements.forEach(el => {
        if (currentUser.role === 'admin') {
            el.classList.remove('hidden');
        } else {
            el.classList.add('hidden');
        }
    });

    // Add click listeners to navigation links
    sidebarNavLinks.forEach(link => {
        link.addEventListener('click', (event) => {
            event.preventDefault();
            const viewId = link.dataset.view;
            showView(viewId);
        });
    });
}

function setupEventListeners() {
    logoutBtn.addEventListener('click', () => {
        data.clearCurrentUser();
        window.location.href = 'index.html';
    });

    // My Outcomes Filters
    searchMyOutcomesBtn.addEventListener('click', renderMyOutcomes);
    myOutcomesFilterType.addEventListener('change', renderMyOutcomes);
    myOutcomesFilterKeywords.addEventListener('input', renderMyOutcomes);
    exportMyOutcomesBtn.addEventListener('click', exportOutcomes);


    // Create Outcome
    selectOutcomeType.addEventListener('change', handleOutcomeTypeSelection);
    outcomeForm.addEventListener('submit', handleOutcomeFormSubmit);
    importBtn.addEventListener('click', () => showNotification('网络异常'));
    downloadTemplateBtn.addEventListener('click', () => showNotification('网络异常'));


    // User Management
    addUserBtn.addEventListener('click', () => {
        userFormContainer.classList.remove('hidden');
        resetUserForm();
    });
    cancelUserEditBtn.addEventListener('click', () => {
        userFormContainer.classList.add('hidden');
        resetUserForm();
    });
    userForm.addEventListener('submit', handleUserFormSubmit);

    // Outcome Type Management
    newOutcomeTypeForm.addEventListener('submit', handleNewOutcomeTypeSubmit);
}

function populateOutcomeTypeSelectors() {
    const outcomeTypes = data.getOutcomeTypes();
    const myOutcomesFilterTypeOptions = ['<option value="">所有类型</option>'];
    const selectOutcomeTypeOptions = ['<option value="">请选择...</option>'];

    outcomeTypes.forEach(type => {
        myOutcomesFilterTypeOptions.push(`<option value="${type.id}">${type.name}</option>`);
        selectOutcomeTypeOptions.push(`<option value="${type.id}">${type.name}</option>`);
    });

    myOutcomesFilterType.innerHTML = myOutcomesFilterTypeOptions.join('');
    selectOutcomeType.innerHTML = selectOutcomeTypeOptions.join('');
}

// --- My Outcomes Logic ---
function renderMyOutcomes() {
    let outcomes = data.getAllOutcomes();
    const filterType = myOutcomesFilterType.value;
    const filterKeywords = myOutcomesFilterKeywords.value.toLowerCase();

    // Filter by current user
    outcomes = outcomes.filter(o => o.submitterId === currentUser.id);

    // Apply type filter
    if (filterType) {
        outcomes = outcomes.filter(o => o.typeId === filterType);
    }

    // Apply keyword filter (simplified: checks title, authors/inventors, project name)
    if (filterKeywords) {
        outcomes = outcomes.filter(o =>
            (o.title && o.title.toLowerCase().includes(filterKeywords)) ||
            (o.authors && o.authors.some(a => a.name.toLowerCase().includes(filterKeywords))) ||
            (o.inventorsDesigners && o.inventorsDesigners.some(id => id.name.toLowerCase().includes(filterKeywords))) ||
            (o.projectName && o.projectName.toLowerCase().includes(filterKeywords)) ||
            (o.projectLeader && o.projectLeader.toLowerCase().includes(filterKeywords))
        );
    }

    if (outcomes.length === 0) {
        myOutcomesListDiv.innerHTML = '<p>暂无相关成果。</p>';
        return;
    }

    const tableHtml = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>类型</th>
                    <th>标题/名称</th>
                    <th>作者/负责人</th>
                    <th>状态</th>
                    <th>提交日期</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${outcomes.map(outcome => `
                    <tr>
                        <td>${outcome.id.substring(0, 8)}</td>
                        <td>${data.getOutcomeTypes().find(t => t.id === outcome.typeId)?.name || '未知'}</td>
                        <td>${outcome.title || outcome.competitionName || outcome.projectName}</td>
                        <td>
                            ${outcome.authors ? outcome.authors.map(a => a.name).join(', ') : ''}
                            ${outcome.inventorsDesigners ? outcome.inventorsDesigners.map(id => id.name).join(', ') : ''}
                            ${outcome.projectLeader || ''}
                        </td>
                        <td>${renderOutcomeStatus(outcome.status)}</td>
                        <td>${outcome.submitDate}</td>
                        <td class="actions">
                            <button class="btn btn-info btn-sm" onclick="viewOutcomeDetails('${outcome.id}')">详情</button>
                            ${(outcome.status === '待审核' || currentUser.role === 'admin') ?
                                `<button class="btn btn-secondary btn-sm" onclick="editOutcome('${outcome.id}')">修改</button>` : ''}
                            ${(outcome.status === '待审核' || currentUser.role === 'admin') ?
                                `<button class="btn btn-danger btn-sm" onclick="deleteOutcomeConfirmation('${outcome.id}')">删除</button>` : ''}
                            ${outcome.status === '已驳回' && outcome.rejectionReason ?
                                `<button class="btn btn-warning btn-sm" onclick="showNotification('驳回原因：${outcome.rejectionReason.replace(/'/g, '&apos;')}', 'error', 10000)">驳回原因</button>` : ''}
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    myOutcomesListDiv.innerHTML = tableHtml;
}

function renderOutcomeStatus(status) {
    let color = '';
    switch (status) {
        case '待审核': color = '#f0ad4e'; break; // Orange
        case '已通过': color = '#5cb85c'; break; // Green
        case '已驳回': color = '#d9534f'; break; // Red
        default: color = '#777'; break;
    }
    return `<span style="color:${color};font-weight:bold;">${status}</span>`;
}

function viewOutcomeDetails(outcomeId) {
    const outcome = data.getAllOutcomes().find(o => o.id === outcomeId);
    if (!outcome) {
        showNotification('成果详情未找到。', 'error');
        return;
    }

    let detailsHtml = `
        <h3>成果详情：${outcome.title || outcome.competitionName || outcome.projectName}</h3>
        <p><strong>类型:</strong> ${data.getOutcomeTypes().find(t => t.id === outcome.typeId)?.name || '未知'}</p>
        <p><strong>提交人:</strong> ${outcome.submitterUsername}</p>
        <p><strong>提交日期:</strong> ${outcome.submitDate}</p>
        <p><strong>状态:</strong> ${renderOutcomeStatus(outcome.status)}</p>
    `;

    const outcomeType = data.getOutcomeTypes().find(t => t.id === outcome.typeId);
    if (outcomeType) {
        [...outcomeType.requiredFields, ...outcomeType.optionalFields].forEach(field => {
            const label = outcomeType.fieldLabels[field];
            const value = outcome[field];
            if (value !== undefined && value !== null && value !== '') {
                if (Array.isArray(value)) {
                    if (value.length > 0) {
                        detailsHtml += `<p><strong>${label}:</strong><ul>`;
                        value.forEach(item => {
                            if (typeof item === 'object') {
                                // Dynamically construct display for complex objects
                                const itemDetails = Object.entries(item)
                                    .map(([key, val]) => {
                                        // Use fieldLabels for known keys within the object if available
                                        const displayKey = outcomeType.fieldLabels[`${field}.${key}`] || key;
                                        // Special handling for boolean values (checkboxes)
                                        if (typeof val === 'boolean') {
                                            return `${displayKey}: ${val ? '是' : '否'}`;
                                        }
                                        return `${displayKey}: ${val}`;
                                    })
                                    .filter(Boolean) // Remove empty entries
                                    .join(', ');
                                detailsHtml += `<li>${itemDetails}</li>`;
                            } else {
                                detailsHtml += `<li>${item}</li>`;
                            }
                        });
                        detailsHtml += `</ul></p>`;
                    }
                } else {
                    detailsHtml += `<p><strong>${label}:</strong> ${value}</p>`;
                }
            }
        });
    }

    if (outcome.status === '已驳回' && outcome.rejectionReason) {
        detailsHtml += `<p><strong>驳回原因:</strong> <span style="color:red;">${outcome.rejectionReason}</span></p>`;
    }
    if (outcome.reviewDate) {
        detailsHtml += `<p><strong>审核日期:</strong> ${outcome.reviewDate}</p>`;
    }


    // This is a simplified modal using a temporary div. In a real app, use a dedicated modal component.
    const tempModal = document.createElement('div');
    tempModal.classList.add('modal-overlay');
    tempModal.innerHTML = `
        <div class="modal-content">
            ${detailsHtml}
            <button class="btn btn-secondary" onclick="this.closest('.modal-overlay').remove()">关闭</button>
        </div>
    `;
    document.body.appendChild(tempModal);

    // Simple modal styling (add this to style.css)
    const modalStyle = `
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            max-width: 80%;
            max-height: 90%;
            overflow-y: auto;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        .modal-content h3 {
            margin-bottom: 20px;
            color: #007bff;
        }
        .modal-content p {
            margin-bottom: 10px;
            line-height: 1.6;
        }
        .modal-content ul {
            margin-top: 5px;
            margin-bottom: 10px;
            padding-left: 20px;
        }
    `;
    const styleTag = document.createElement('style');
    styleTag.textContent = modalStyle;
    document.head.appendChild(styleTag);
}


function editOutcome(outcomeId) {
    const outcome = data.getAllOutcomes().find(o => o.id === outcomeId);
    if (!outcome) {
        showNotification('成果未找到。', 'error');
        return;
    }

    showView('createOutcome'); // Switch to create outcome view
    selectOutcomeType.value = outcome.typeId; // Set the type
    // Pass the initial outcome data to handleOutcomeTypeSelection for pre-filling fields
    handleOutcomeTypeSelection(null, outcome);

    // Set hidden ID for update operation
    outcomeForm.dataset.editId = outcome.id;
    currentOutcomeTypeTitle.textContent = `修改成果: ${outcome.title || outcome.competitionName || outcome.projectName}`;
    outcomeForm.querySelector('button[type="submit"]').textContent = '更新成果';
}

function deleteOutcomeConfirmation(outcomeId) {
    if (confirm('确定要删除此成果吗？此操作不可逆。')) {
        const result = data.deleteOutcome(outcomeId);
        if (result.success) {
            showNotification(result.message, 'success');
            renderMyOutcomes(); // Re-render the list
            if (currentActiveView === 'outcomeReview') {
                renderPendingOutcomes(); // Also update review list if applicable
            }
        } else {
            showNotification(result.message, 'error');
        }
    }
}

function exportOutcomes() {
    const outcomesToExport = data.getAllOutcomes().filter(o => o.submitterId === currentUser.id); // Or current filtered list
    if (outcomesToExport.length === 0) {
        showNotification('没有成果可以导出。', 'info');
        return;
    }

    let csvContent = "data:text/csv;charset=utf-8,\uFEFF"; // Add BOM for Chinese characters
    const headers = ["ID", "类型", "标题/名称", "作者/负责人", "状态", "提交日期"];
    csvContent += headers.join(",") + "\n";

    outcomesToExport.forEach(outcome => {
        const typeName = data.getOutcomeTypes().find(t => t.id === outcome.typeId)?.name || '未知';
        const titleOrName = outcome.title || outcome.competitionName || outcome.projectName || '';
        const authorsOrLeader = outcome.authors ? outcome.authors.map(a => a.name).join(';') :
                                outcome.inventorsDesigners ? outcome.inventorsDesigners.map(id => id.name).join(';') :
                                outcome.projectLeader || '';
        const row = [outcome.id, typeName, `"${titleOrName.replace(/"/g, '""')}"`, `"${authorsOrLeader.replace(/"/g, '""')}"`, outcome.status, outcome.submitDate];
        csvContent += row.join(",") + "\n";
    });

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `my_outcomes_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showNotification('成果已导出为CSV文件。', 'success');
}


// --- Create/Edit Outcome Logic ---
function resetOutcomeForm() {
    outcomeForm.reset();
    outcomeForm.classList.add('hidden');
    commonOutcomeFieldsDiv.innerHTML = '';
    specificOutcomeFieldsDiv.innerHTML = '';
    selectOutcomeType.value = '';
    outcomeForm.dataset.editId = ''; // Clear edit ID
    currentOutcomeTypeTitle.textContent = '';
    outcomeForm.querySelector('button[type="submit"]').textContent = '提交成果';

    // Clear attachment info message
    const infoSpan = document.querySelector('.uploaded-file-info');
    if (infoSpan) infoSpan.remove();
}

/**
 * Generates HTML for a single item in a dynamic list (e.g., author, inventor).
 * @param {string} fieldName - The base name of the field (e.g., 'authors', 'inventorsDesigners').
 * @param {object} valueObj - The object containing current values for this item (e.g., {name: '张三', unit: 'XX大学', isFirstAuthor: true}).
 * @returns {string} HTML string for the list item.
 */
function listItemTemplate(fieldName, valueObj) {
    let inputHtml = '';
    if (fieldName === 'authors') {
        inputHtml = `
            <input type="text" name="${fieldName}Name" placeholder="姓名" value="${valueObj?.name || ''}" required>
            <input type="text" name="${fieldName}Unit" placeholder="所属单位" value="${valueObj?.unit || ''}">
            <label><input type="checkbox" name="${fieldName}FirstAuthor" ${valueObj?.isFirstAuthor ? 'checked' : ''}>第一作者</label>
            <label><input type="checkbox" name="${fieldName}CommAuthor" ${valueObj?.isCommAuthor ? 'checked' : ''}>通讯作者</label>
        `;
    } else if (fieldName === 'inventorsDesigners' || fieldName === 'participants') {
        inputHtml = `
            <input type="text" name="${fieldName}Name" placeholder="姓名" value="${valueObj?.name || ''}" required>
        `;
    } else if (fieldName === 'participantsRanked') {
        inputHtml = `
            <input type="text" name="${fieldName}Name" placeholder="姓名" value="${valueObj?.name || ''}" required>
            <input type="number" name="${fieldName}Rank" placeholder="排名" value="${valueObj?.rank || ''}" min="1">
        `;
    }
    return `
        <div class="item-list-entry">
            ${inputHtml}
            <button type="button" class="remove-btn" onclick="removeItemFromList(this)">移除</button>
        </div>
    `;
}

/**
 * Adds a new empty item entry to a dynamic list.
 * @param {string} listId - The ID of the container div for the list (e.g., 'authorsList').
 * @param {string} fieldName - The base name of the field (e.g., 'authors').
 * @param {string} typeId - The ID of the current outcome type.
 */
function addItemToList(listId, fieldName, typeId) {
    const listContainer = document.getElementById(listId);
    if (!listContainer) {
        console.error(`List container with ID ${listId} not found.`);
        return;
    }
    const newEntryHtml = listItemTemplate(fieldName, {}); // Pass empty object for new item
    listContainer.innerHTML += newEntryHtml; // Append new entry
}

function removeItemFromList(button) {
    button.closest('.item-list-entry').remove();
}


/**
 * Handles the selection of an outcome type, dynamically generating form fields.
 * @param {Event} event - The change event from the select element, or null if called directly.
 * @param {object} initialOutcomeData - Optional existing outcome data for pre-filling fields during edit.
 */
function handleOutcomeTypeSelection(event, initialOutcomeData = null) {
    console.log("handleOutcomeTypeSelection called. Event:", event); // 新增
    const selectedTypeId = event ? event.target.value : selectOutcomeType.value;
    console.log("Selected Type ID:", selectedTypeId); // 新增

    const outcomeType = data.getOutcomeTypes().find(t => t.id === selectedTypeId);
    console.log("Found outcomeType object:", outcomeType); // 新增

    commonOutcomeFieldsDiv.innerHTML = '';
    specificOutcomeFieldsDiv.innerHTML = '';
    outcomeForm.classList.add('hidden');
    currentOutcomeTypeTitle.textContent = outcomeType ? `录入${outcomeType.name}信息` : '';

    if (!outcomeType) {
        console.log("No outcomeType found or '请选择...' selected. Returning."); // 新增
        return;
    }

    outcomeForm.classList.remove('hidden');
    console.log("Outcome form shown. Preparing to render fields for:", outcomeType.name); // 新增

    const fieldsToRender = [...outcomeType.requiredFields, ...outcomeType.optionalFields];

    fieldsToRender.forEach(field => {
        console.log("Rendering field:", field); // 新增
        // 在这里，也就是你错误日志所指的第 546 行附近，再次打印 outcomeType
        console.log("Inside forEach, outcomeType is:", outcomeType); // <--- 关键调试点
        console.log("Accessing outcomeType.fieldLabels:", outcomeType.fieldLabels); // 尝试访问一个属性

        const label = outcomeType.fieldLabels[field] || field;
        const placeholder = outcomeType.fieldPlaceholders[field] || '';
        const isRequired = outcomeType.requiredFields.includes(field);
        const inputType = outcomeType.fieldTypes?.[field] || 'text';



        // 下面是你之前提到可能出问题的地方
        // 使用可选链 ?. 来安全地访问 dropdownOptions 属性
        const options = outcomeType.dropdownOptions?.[field];
        console.log(`Field: ${field}, Options from dropdownOptions:`, options); // 新增


        const currentValue = initialOutcomeData ? initialOutcomeData[field] : '';

        let inputHtml = '';
        let targetDiv = commonOutcomeFieldsDiv;

        if (['authors', 'inventorsDesigners', 'participants', 'participantsRanked'].includes(field)) {
            // ... (省略内部逻辑，但这里的 outcomeType 也可能出问题)
            targetDiv = specificOutcomeFieldsDiv;
            const listId = `${field}List`;
            const itemsHtml = (currentValue && currentValue.length > 0) ?
                currentValue.map(item => listItemTemplate(field, item)).join('') : ''; // listItemTemplate 内部没有使用 outcomeType

            inputHtml = `
                <div class="input-group outcome-field-group">
                    <h4>${label}${isRequired ? ' (必填)' : ''}</h4>
                    <div id="${listId}">
                        ${itemsHtml}
                    </div>
                    <button type="button" class="add-item-btn" onclick="addItemToList('${listId}', '${field}', '${selectedTypeId}')">添加</button>
                </div>
            `;
        } else if (options) {
            targetDiv = specificOutcomeFieldsDiv;
            inputHtml = `
                <div class="input-group">
                    <label for="${field}">${label}${isRequired ? ' (必填)' : ''}:</label>
                    <select id="${field}" name="${field}" ${isRequired ? 'required' : ''}>
                        <option value="">请选择</option>
                        ${options.map(opt => `<option value="${opt}" ${currentValue === opt ? 'selected' : ''}>${opt}</option>`).join('')}
                    </select>
                </div>
            `;
        } else if (inputType === 'textarea') {
            inputHtml = `
                <div class="input-group">
                    <label for="${field}">${label}${isRequired ? ' (必填)' : ''}:</label>
                    <textarea id="${field}" name="${field}" rows="4" placeholder="${placeholder}" ${isRequired ? 'required' : ''}>${currentValue}</textarea>
                </div>
            `;
        }
        else {
            inputHtml = `
                <div class="input-group">
                    <label for="${field}">${label}${isRequired ? ' (必填)' : ''}:</label>
                    <input type="${inputType}" id="${field}" name="${field}" placeholder="${placeholder}" value="${currentValue}" ${isRequired ? 'required' : ''}>
                </div>
            `;
        }
        targetDiv.innerHTML += inputHtml;
    });

    // Handle attachment field value if editing (display file name, no actual file re-upload)
    const attachmentDiv = document.querySelector('.attachment-upload');
    if (attachmentDiv) {
        let infoSpan = attachmentDiv.querySelector('.uploaded-file-info');
        if (infoSpan) infoSpan.remove(); // Remove existing info first

        if (initialOutcomeData && initialOutcomeData.attachmentInfo) {
            infoSpan = document.createElement('span');
            infoSpan.classList.add('uploaded-file-info');
            infoSpan.textContent = `已上传文件: ${initialOutcomeData.attachmentInfo.fileName}`;
            attachmentDiv.appendChild(infoSpan);
        }
    }
}


function getOutcomeFormData(form) {
    const formData = {};
    const outcomeTypeId = selectOutcomeType.value;
    const outcomeType = data.getOutcomeTypes().find(t => t.id === outcomeTypeId);

    if (!outcomeType) {
        showNotification('请选择成果类型！', 'error');
        return null;
    }

    formData.typeId = outcomeTypeId;

    // Get specific fields
    const fields = [...outcomeType.requiredFields, ...outcomeType.optionalFields];
    for (const field of fields) {
        if (['authors', 'inventorsDesigners', 'participants', 'participantsRanked'].includes(field)) {
            const listItems = document.querySelectorAll(`#${field}List .item-list-entry`);
            const itemList = [];
            listItems.forEach(item => {
                const nameInput = item.querySelector(`input[name="${field}Name"]`);
                const name = nameInput?.value.trim();

                if (!name && outcomeType.requiredFields.includes(field)) { // Only if the list itself is required
                    showNotification(`${outcomeType.fieldLabels[field]} (姓名) 是必填项！`, 'error');
                    nameInput.focus(); // Focus on the problematic input
                    return null; // Indicate validation failure
                }
                if (!name) return; // Skip if name is empty and not required for this item

                const itemData = { name };
                if (field === 'authors') {
                    itemData.unit = item.querySelector(`input[name="${field}Unit"]`)?.value.trim();
                    itemData.isFirstAuthor = item.querySelector(`input[name="${field}FirstAuthor"]`)?.checked || false;
                    itemData.isCommAuthor = item.querySelector(`input[name="${field}CommAuthor"]`)?.checked || false;
                } else if (field === 'participantsRanked') {
                    const rankInput = item.querySelector(`input[name="${field}Rank"]`);
                    itemData.rank = parseInt(rankInput?.value) || null;
                    if (isRequired && (!itemData.rank || itemData.rank <= 0)) { // Assuming rank is required if field is required
                        showNotification(`${outcomeType.fieldLabels[field]} (排名) 必须是有效的正整数！`, 'error');
                        rankInput.focus();
                        return null; // Indicate validation failure
                    }
                }
                itemList.push(itemData);
            });
            // If any item failed validation, return null from here as well
            if (itemList.includes(null)) return null;

            if (itemList.length === 0 && outcomeType.requiredFields.includes(field)) {
                 showNotification(`${outcomeType.fieldLabels[field]} 不能为空！`, 'error');
                 return null;
            }
            formData[field] = itemList;
        } else {
            const element = document.getElementById(field);
            if (element) {
                let value = element.value.trim();
                if (element.type === 'number' || element.type === 'range') {
                    value = parseFloat(value);
                    if (isNaN(value)) value = null;
                }
                if (outcomeType.requiredFields.includes(field) && (value === null || value === '')) {
                    showNotification(`${outcomeType.fieldLabels[field]} 是必填项！`, 'error');
                    element.focus();
                    return null;
                }
                formData[field] = value;
            }
        }
    }

    // Handle attachment (simulated)
    if (outcomeAttachmentInput.files.length > 0) {
        const file = outcomeAttachmentInput.files[0];
        formData.attachmentInfo = {
            fileName: file.name,
            fileSize: file.size,
            fileType: file.type
        };
        // In a real system, you'd upload the file to a server here.
    } else if (form.dataset.editId) { // Check if it's an edit operation
        // If editing and no new file selected, retain existing attachment info
        const existingOutcome = data.getAllOutcomes().find(o => o.id === form.dataset.editId);
        if (existingOutcome && existingOutcome.attachmentInfo) {
            formData.attachmentInfo = existingOutcome.attachmentInfo;
        }
    }


    return formData;
}

function handleOutcomeFormSubmit(event) {
    event.preventDefault();

    const outcomeData = getOutcomeFormData(outcomeForm);
    if (!outcomeData) {
        return; // Validation failed (error message already shown)
    }

    const editId = outcomeForm.dataset.editId;
    let result;

    if (editId) {
        // Update existing outcome
        const originalOutcome = data.getAllOutcomes().find(o => o.id === editId);
        if (originalOutcome.status === '已通过' && currentUser.role !== 'admin') {
             // For normal users, restrict modification of non-optional fields if already approved
             // This is a simplified check. A robust system would compare field definitions.
             const outcomeType = data.getOutcomeTypes().find(t => t.id === originalOutcome.typeId);
             // Assume all required fields are critical and cannot be changed by normal user after approval
             const criticalFields = outcomeType.requiredFields;
             let hasCriticalChanges = false;

             for (const field of criticalFields) {
                 // Compare only if the field exists in new data and it's a critical field
                 if (outcomeData.hasOwnProperty(field)) {
                    // Deep compare for arrays/objects, simple compare for primitives
                    const originalValue = originalOutcome[field];
                    const newValue = outcomeData[field];

                    if (JSON.stringify(originalValue) !== JSON.stringify(newValue)) {
                        hasCriticalChanges = true;
                        break;
                    }
                 }
             }

             if (hasCriticalChanges) {
                 showNotification('已通过审核的成果，普通用户仅能修改非核心（选填）信息。', 'error');
                 return;
             }
        }
        result = data.updateOutcome(editId, outcomeData);
    } else {
        // Add new outcome
        result = data.addOutcome(outcomeData);
    }

    if (result.success) {
        showNotification(result.message, 'success');
        resetOutcomeForm();
        renderMyOutcomes(); // Refresh my outcomes
        if (currentUser.role === 'admin') {
            renderPendingOutcomes(); // Also refresh pending outcomes for admin
        }
    } else {
        showNotification(result.message, 'error');
    }
}


// --- Outcome Review Logic (Admin Only) ---
function renderPendingOutcomes() {
    if (currentUser.role !== 'admin') {
        pendingOutcomesListDiv.innerHTML = '<p>您没有权限查看此内容。</p>';
        return;
    }

    const pending = data.getAllOutcomes().filter(o => o.status === '待审核');

    if (pending.length === 0) {
        pendingOutcomesListDiv.innerHTML = '<p>暂无待审核成果。</p>';
        return;
    }

    const tableHtml = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>类型</th>
                    <th>标题/名称</th>
                    <th>提交人</th>
                    <th>提交日期</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${pending.map(outcome => `
                    <tr>
                        <td>${outcome.id.substring(0, 8)}</td>
                        <td>${data.getOutcomeTypes().find(t => t.id === outcome.typeId)?.name || '未知'}</td>
                        <td>${outcome.title || outcome.competitionName || outcome.projectName}</td>
                        <td>${outcome.submitterUsername}</td>
                        <td>${outcome.submitDate}</td>
                        <td class="actions">
                            <button class="btn btn-info btn-sm" onclick="viewOutcomeDetails('${outcome.id}')">详情</button>
                            <button class="btn btn-success btn-sm" onclick="approveOutcomeAction('${outcome.id}')">通过</button>
                            <button class="btn btn-danger btn-sm" onclick="rejectOutcomeAction('${outcome.id}')">驳回</button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    pendingOutcomesListDiv.innerHTML = tableHtml;
}

function approveOutcomeAction(outcomeId) {
    if (confirm('确定要通过此成果审核吗？')) {
        const result = data.approveOutcome(outcomeId);
        if (result.success) {
            showNotification(`成果 "${result.outcome.title || result.outcome.competitionName || result.outcome.projectName}" 已通过审核。`, 'success');
            renderPendingOutcomes();
        } else {
            showNotification(result.message, 'error');
        }
    }
}

function rejectOutcomeAction(outcomeId) {
    const reason = prompt('请输入驳回原因:');
    if (reason === null) return; // User cancelled
    if (reason.trim() === '') {
        showNotification('驳回原因不能为空！', 'error');
        return;
    }

    const result = data.rejectOutcome(outcomeId, reason);
    if (result.success) {
        showNotification(`成果 "${result.outcome.title || result.outcome.competitionName || result.outcome.projectName}" 已被驳回。`, 'success');
        renderPendingOutcomes();
    } else {
        showNotification(result.message, 'error');
    }
}

// --- User Management Logic (Admin Only) ---
function renderUserManagement() {
    if (currentUser.role !== 'admin') {
        userListDiv.innerHTML = '<p>您没有权限查看此内容。</p>';
        return;
    }

    const allUsers = data.getAllUsers();
    if (allUsers.length === 0) {
        userListDiv.innerHTML = '<p>暂无用户。</p>';
        return;
    }

    const tableHtml = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${allUsers.map(user => `
                    <tr>
                        <td>${user.id.substring(0, 8)}</td>
                        <td>${user.username}</td>
                        <td>${user.role === 'admin' ? '管理员' : '普通用户'}</td>
                        <td class="actions">
                            <button class="btn btn-secondary btn-sm" onclick="editUser('${user.id}')">编辑</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteUserConfirmation('${user.id}')" ${user.id === currentUser.id ? 'disabled' : ''}>删除</button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    userListDiv.innerHTML = tableHtml;
}

function resetUserForm() {
    userForm.reset();
    userIdInput.value = '';
    userPasswordInput.value = ''; // Ensure password field is cleared for security
    userForm.querySelector('button[type="submit"]').textContent = '保存用户';
    userUsernameInput.disabled = false; // Enable username for new user
    userPasswordInput.placeholder = ''; // Clear placeholder if it was set for edit
}

function editUser(userId) {
    const user = data.getAllUsers().find(u => u.id === userId);
    if (!user) {
        showNotification('用户未找到。', 'error');
        return;
    }
    userFormContainer.classList.remove('hidden');
    userIdInput.value = user.id;
    userUsernameInput.value = user.username;
    userUsernameInput.disabled = true; // Prevent changing username for existing users in this prototype
    userRoleSelect.value = user.role;
    userForm.querySelector('button[type="submit"]').textContent = '更新用户';
    userPasswordInput.placeholder = '留空则不修改密码';
}

function deleteUserConfirmation(userId) {
    if (userId === currentUser.id) {
        showNotification('您不能删除当前登录的管理员账户！', 'error');
        return;
    }
    if (confirm('确定要删除此用户吗？此操作不可逆。')) {
        const result = data.deleteUser(userId);
        if (result.success) {
            showNotification(result.message, 'success');
            renderUserManagement();
        } else {
            showNotification(result.message, 'error');
        }
    }
}

function handleUserFormSubmit(event) {
    event.preventDefault();
    const id = userIdInput.value;
    const username = userUsernameInput.value.trim();
    const password = userPasswordInput.value.trim();
    const role = userRoleSelect.value;

    if (!username) {
        showNotification('用户名是必填项！', 'error');
        return;
    }

    let result;
    if (id) {
        // Update user
        result = data.updateUser(id, username, password, role);
    } else {
        // Add user
        if (!password) {
            showNotification('新用户密码是必填项！', 'error');
            return;
        }
        result = data.addUser(username, password, role);
    }

    if (result.success) {
        showNotification(result.message, 'success');
        resetUserForm();
        userFormContainer.classList.add('hidden');
        renderUserManagement();
    } else {
        showNotification(result.message, 'error');
    }
}


// --- Outcome Type Management Logic (Admin Only) ---
function renderOutcomeTypesManagement() {
    if (currentUser.role !== 'admin') {
        outcomeTypesListUl.innerHTML = '<p>您没有权限查看此内容。</p>';
        return;
    }

    const allTypes = data.getOutcomeTypes();
    if (allTypes.length === 0) {
        outcomeTypesListUl.innerHTML = '<p>暂无成果类型。</p>';
        return;
    }

    outcomeTypesListUl.innerHTML = allTypes.map(type => `
        <li>
            ${type.name} (${type.isCustom ? '自定义' : '预设'})
            ${type.isCustom ? `<button class="btn btn-danger btn-sm" onclick="deleteCustomOutcomeTypeAction('${type.id}')">删除</button>` : ''}
        </li>
    `).join('');
}

function handleNewOutcomeTypeSubmit(event) {
    event.preventDefault();
    const newTypeName = newTypeNameInput.value.trim();
    if (!newTypeName) {
        showNotification('成果类型名称不能为空！', 'error');
        return;
    }

    const result = data.addCustomOutcomeType(newTypeName);
    if (result.success) {
        showNotification(result.message, 'success');
        newTypeNameInput.value = '';
        renderOutcomeTypesManagement();
        populateOutcomeTypeSelectors(); // Update select dropdowns
    } else {
        showNotification(result.message, 'error');
    }
}

function deleteCustomOutcomeTypeAction(typeId) {
    if (confirm('确定要删除此自定义成果类型吗？')) {
        const result = data.deleteCustomOutcomeType(typeId);
        if (result.success) {
            showNotification(result.message, 'success');
            renderOutcomeTypesManagement();
            populateOutcomeTypeSelectors(); // Update select dropdowns
        } else {
            showNotification(result.message, 'error');
        }
    }
}
